#pragma once
#include "nodes\DynamicSpriteNode.h"
#include <vector>
#include "utils\mtrand.h"
#include "cvar\CVar.h"
#include "game\World.h"
#include "collision\CollisionDetector.h"

class Swimmer : public ds::DynamicSpriteNode {

struct Entry {
	ds::Sprite* sprite;
	float timer;
	ds::Vec2 start;
	ds::Vec2 end;
	ds::Vec2 mid;
	ds::CDHandle handle;
	ds::Vec2 velocity;
	bool targetting;
	int energy;
	std::vector<ds::Sprite*> tails;
};

typedef std::vector<Entry> Entries;

public:
	Swimmer() : ds::DynamicSpriteNode("Swimmer","TexturesMaterial",ds::SCM_MODULATE) , m_Target(ds::Vec2(500,0)) 
		, m_Left(true) , m_CD(gEngine->getCollisionDetector()) {
			rand.seed(GetTickCount());
	}
	~Swimmer(void);
	void init();
	void update(float elapsed);
	void create(uint32 total);
	void setTarget(const ds::Vec2& target) {
		m_Target = target;
	}
	void removeByHandle(ds::CDHandle handle);	
	int handleHit(ds::CDHandle handle);
	void clear();
private:
	ds::Vec2 getNewPosition(const ds::Vec2& target,const ds::Vec2& pos,float distance,float add) {
		ds::Vec2 ret = pos;
		float dx = target.x - pos.x;
		float dy = target.y - pos.y;
		float dist = sqrt( dx * dx + dy * dy);
		if ( dist > distance ) {
			ret.x = pos.x + dx * add;
			ret.y = pos.y + dy * add;
		}
		return ret;
	}
	ds::Vec2 getCorrectedTarget(Entry* e);
	void moveTail(Entry* e);
	void checkTargettting();
	void moveAll(float elapsed);
	void checkMovement(Entry* e);
	MTRand_open rand;
	ds::CollisionDetector& m_CD;
	Entries m_Entries;
	ds::Vec2 m_Target;
	bool m_Left;
	bool m_Targetting;
};

